//
//  UIView+Extension.swift
//  MattressTool
//
//  Created by Coder Yang on 2023/11/19.
//

import UIKit

extension UIView {
    
    /// 边距
    var inset: CGFloat {
        Configs.BaseDimensions.inset
    }
    
    /// 默认视图高度
    var viewHeight: CGFloat {
        Configs.BaseDimensions.viewHeight
    }
    
    /// 圆角半径
    var cornerRadius: CGFloat {
        Configs.BaseDimensions.cornerRadius
    }
    
    /// 边框宽度
    var borderWidth: CGFloat {
        Configs.BaseDimensions.borderWidth
    }
    
    /// 画圆角
    func roundCorners(corners: UIRectCorner = .allCorners,
                      radius: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds,
                                byRoundingCorners: corners,
                                cornerRadii: CGSize(width: radius,
                                                    height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
    
    /// 取消圆角
    func noCornerMask() {
        layer.mask = nil
    }
    
    /// 加载 Loading
    func makeActivity(message: String) {
        
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = cornerRadius
        view.layer.masksToBounds = true
        
        let activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.large)
        activityIndicatorView.color = .text
        activityIndicatorView.startAnimating()
        
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let size = message.boundingRect(with: CGSize(width: 220.rpx, height: 1000),
                                        options: option,
                                        attributes: attributes, context: nil).size
        let label = UILabel(text: message, color: .text, font: .body, alignment: .center, lines: 0)
        
        view.addSubview(activityIndicatorView)
        view.addSubview(label)
        
        let width = max(activityIndicatorView.size.width, size.width) + 2 * inset
        let height = activityIndicatorView.size.height + size.height + 3 * inset
        
        view.frame = CGRect(x: 0, y: 0, width: width, height: height)
        
        activityIndicatorView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(inset)
            make.centerX.equalToSuperview()
        }
        
        label.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-inset)
            make.centerX.equalToSuperview()
            make.width.equalTo(width - 2 * inset)
        }
        view.addShadow(ofColor: .placeholder)
        self.showToast(view, duration: Double.infinity, position: .center)
    }
}
